package com.mycompany.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.mycompany.dao.CommonDao;
import com.mycompany.dao.SchoolDao;
import com.mycompany.entity.School;
import com.mycompany.entity.Score;
import com.mycompany.entity.Teacher;

@Service
public class SchoolServiceImpl extends DefaultCommonService<Long, School>
		implements SchoolService {
	@Autowired
	private SchoolDao schoolDao;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private ScoreService scoreService;
	
	@Override
	protected CommonDao<Long, School> getDao() {
		return schoolDao;
	}

	@Override
	public List<School> getAllSchool() {
		return schoolDao.getAllSchool();
	}

	@Override
	public void insertSchoolWithAllInfo(School school) {
		super.insert(school);

		School s = schoolDao.getSchoolByExample(school);
		if (!CollectionUtils.isEmpty(school.getTeachers())) {
			for (Teacher teacher : school.getTeachers()) {
				teacher.setSchool(s);
				teacherService.insert(teacher);
			}
		}
		if(!CollectionUtils.isEmpty(school.getScores())) {
			for (Score score : school.getScores()) {
				score.setSchool(s);
				scoreService.insert(score);
			}
		}
	}

	@Override
	public School getSchoolByExample(School example) {
		return schoolDao.getSchoolByExample(example);
	}

	@Override
	public School getSchoolByName(String sname) {
		return schoolDao.getSchoolByName(sname);
	}

	@Override
	public void deleteSchoolWithAllInfo(School school) {
		super.delete(school);
		if (!CollectionUtils.isEmpty(school.getTeachers())) {
			for (Teacher teacher : school.getTeachers()) {
				teacherService.delete(teacher);
			}
		}
		if(!CollectionUtils.isEmpty(school.getScores())) {
			for (Score score : school.getScores()) {
				scoreService.delete(score);
			}
		}
	}

	@Override
	public void updateSchoolWithAllInfo(School school) {
		super.update(school);
		if (!CollectionUtils.isEmpty(school.getTeachers())) {
			for (Teacher teacher : school.getTeachers()) {
				teacherService.update(teacher);
			}
		}
		if(!CollectionUtils.isEmpty(school.getScores())) {
			for (Score score : school.getScores()) {
				scoreService.update(score);
			}
		}
	}
}
